/*
 * @Author: Author && Email
 * @Date: 2024-03-17 22:10:12
 * @LastEditors: Author && Email
 * @LastEditTime: 2024-03-17 22:26:49
 * @FilePath: \MDK-ARMd:\WorkSpace\PRJ\Washing_machine\software\Washing_machine_V1\User\bsp\bsp_adc.c
 * @Description: 
 * 
 * Copyright (c) 2024 by ${git_name_email}, All Rights Reserved. 
 */
#include "bsp_adc.h"

#define ADC1_CHANNEL_CNT 2 	        //采样通道数
#define ADC1_CHANNEL_FRE 10	        //单个通道采样次数，用来取平均值
uint16_t adc1_val_buf[ADC1_CHANNEL_CNT*ADC1_CHANNEL_FRE]; //传递给DMA存放多通道采样值的数组
uint32_t adc1_aver_val[ADC1_CHANNEL_CNT] = {0}; //计算多通道的平均采样值的过程数组
uint16_t value[ADC1_CHANNEL_CNT] = {0};//多通道的平均采样值的数组
uint32_t voltage[ADC1_CHANNEL_CNT] = {0};
uint16_t val_ratio[ADC1_CHANNEL_CNT] = {0};
/**
 * @description: ADC初始化
 * @return {*}
 */
void bsp_adc_init(void)
{
    HAL_ADC_Start_DMA(&hadc1, (uint32_t *)adc1_val_buf, ADC1_CHANNEL_CNT*ADC1_CHANNEL_FRE); /* 启用DMA */
    HAL_ADCEx_Calibration_Start(&hadc1);        /* ADC校准 */
    HAL_ADC_Start(&hadc1);                      /* 启用ADC转换 */
}


uint32_t map(uint32_t x, uint32_t in_min, uint32_t in_max, uint32_t out_min, uint32_t out_max)
{
	if(x < in_min)
	{
		return out_min;
	}
	if(x > in_max)
	{
		return out_max;
	}
	return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

void bsp_adc_calc(void)
{
    uint8_t i;
    
    for(i = 0; i < ADC1_CHANNEL_CNT; i++)
    {
        adc1_aver_val[i] = 0;
    }
    /* 在采样值数组中分别取出每个通道的采样值并求和 */
    for(i = 0; i < ADC1_CHANNEL_FRE; i++)
    {
        adc1_aver_val[0] +=  adc1_val_buf[i*ADC1_CHANNEL_CNT+0];
        adc1_aver_val[1] +=  adc1_val_buf[i*ADC1_CHANNEL_CNT+1];
    }
    /* 依次对每个通道采样值求平均值 */
    for(i = 0; i < ADC1_CHANNEL_CNT; i++)
    {
        value[i] = adc1_aver_val[i] / ADC1_CHANNEL_FRE;
    }
    /* 依次对每个通道采样值求平均值 */
    for(i = 0; i < ADC1_CHANNEL_CNT; i++)
    {
        voltage[i] = (uint32_t) 3300000/4096*value[i]/1000;
		val_ratio[i] = (uint16_t)map(voltage[i], 1000, 2000, 0, 100);
    }
}
